package com.share.rules.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.rules.api.domain.*;
import com.share.rules.config.DroolsHelper;
import com.share.rules.mapper.FeeRuleMapper;
import com.share.rules.service.IFeeRuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FeeRuleServiceImpl extends ServiceImpl<FeeRuleMapper, FeeRule> implements IFeeRuleService {

    private final KieContainer kieContainer;

    /**
     * 查询费用规则列表
     */
    @Override
    public List<FeeRule> selectFeeRuleList(FeeRule feeRule) {
        return baseMapper.selectFeeRuleList(feeRule);
    }

    /**
     * 获取全部费用规则
     */
    @Override
    public List<FeeRule> getALLFeeRuleList() {
        return this.baseMapper.selectList(new LambdaQueryWrapper<FeeRule>().eq(FeeRule::getStatus, "1"));
    }

    /**
     * 计算订单费用
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm feeRuleRequestForm) {
        // 参数校验
        if (feeRuleRequestForm == null || feeRuleRequestForm.getFeeRuleId() == null) {
            log.error("计算订单费用失败：请求参数为空或规则ID为空");
            throw new IllegalArgumentException("订单费用计算参数不能为空");
        }

        KieSession kieSession = null;
        try {
            // 封装传入对象
            FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
            feeRuleRequest.setDurations(feeRuleRequestForm.getDuration());
            log.info("传入参数：{}", JSON.toJSONString(feeRuleRequest));

            // 获取最新订单费用规则
            FeeRule feeRule = this.baseMapper.selectById(feeRuleRequestForm.getFeeRuleId());
            if (feeRule == null) {
                log.error("计算订单费用失败：未找到规则ID为{}的费用规则", feeRuleRequestForm.getFeeRuleId());
                throw new ServiceException("未找到匹配的费用规则");
            }

            // 规则内容校验（可选）
            if (StringUtils.isBlank(feeRule.getRule())) {
                log.error("计算订单费用失败：规则ID为{}的规则内容为空", feeRuleRequestForm.getFeeRuleId());
                throw new ServiceException("费用规则内容为空");
            }

            // 创建KieSession
            kieSession = DroolsHelper.loadForRule(feeRule.getRule());

            // 封装返回对象
            FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
            kieSession.setGlobal("feeRuleResponse", feeRuleResponse);
            // 设置订单对象
            kieSession.insert(feeRuleRequest);
            // 触发规则
            int rulesFired = kieSession.fireAllRules();
            log.info("触发了{}条规则", rulesFired);

            // 封装返回对象
            FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
            feeRuleResponseVo.setTotalAmount(new BigDecimal(feeRuleResponse.getTotalAmount()));
            feeRuleResponseVo.setFreePrice(new BigDecimal(feeRuleResponse.getFreePrice()));
            feeRuleResponseVo.setExceedPrice(new BigDecimal(feeRuleResponse.getExceedPrice()));
            feeRuleResponseVo.setFreeDescription(feeRuleResponse.getFreeDescription());
            feeRuleResponseVo.setExceedDescription(feeRuleResponse.getExceedDescription());

            log.info("计算结果：{}", JSON.toJSONString(feeRuleResponseVo));
            return feeRuleResponseVo;
        } catch (Exception e) {
            // 记录详细异常信息
            log.error("计算订单费用异常：{}", e.getMessage(), e);
            // 根据业务需求选择抛出特定异常或返回默认值
            throw new ServiceException("订单费用计算失败，请稍后重试");
        } finally {
            // 确保KieSession资源释放
            DroolsHelper.closeSession(kieSession);
        }
    }
}
